import { createHash, randomBytes } from 'crypto'
import { hash } from 'argon2'
import { container } from 'tsyringe'
import { ROOT } from './tokens'
import { join } from 'path'
import { readFileSync } from 'fs'
import { sign, verify } from "jsonwebtoken";

export function createToken<T extends object>(payload: T, expiresIn: string | number = '15m') {
    const root = container.resolve(ROOT)
    const data = JSON.parse(readFileSync(join(root, 'data/plugins/@sker/hasura.json'), 'utf-8'))
    return sign(payload, data.JWT_SECRET, {
        algorithm: data.JWT_ALGORITHM,
        expiresIn: expiresIn
    })
}

export function verifyToken<T extends object>(token: string) {
    const root = container.resolve(ROOT)
    const data = JSON.parse(readFileSync(join(root, 'data/plugins/@sker/hasura.json'), 'utf-8'))
    const result = verify(token, data.JWT_SECRET, {
        algorithms: data.JWT_ALGORITHM
    })
    return result
}

export function md5(data: string) {
    return createHash('md5').update(data).digest('hex')
}

export function randomSalt() {
    return randomBytes(12).toString('base64').toLocaleLowerCase()
}

export function getTimestap() {
    return parseInt(`${Date.now() / 1000}`, 10)
}

export function encryptPassword(password: string, salt: string) {
    return hash(password, { salt: Buffer.from(salt) })
}
